package com.company;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @date : 2021-12-13 下午10:07
 * SimpleDateFormat类线程不安全问题
 */

public class P010_SimpleDateFormatThreadUnsafe {

    public static class SimpleDateFormat01 {

        private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private static ExecutorService service = new ThreadPoolExecutor(50,
                100, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100),
                new MyThreadFactory("SimpleDateFormat"));

        public static class MyThreadFactory implements ThreadFactory {

            private final String namePrefix;

            private final AtomicInteger nextId = new AtomicInteger(1);

            MyThreadFactory(String whatFeatureOfGroup) {
                namePrefix = "MyThreadFactory-" + whatFeatureOfGroup + "-Worker-";
            }

            @Override
            public Thread newThread(Runnable r) {
                String name = namePrefix + nextId.getAndIncrement();
                return new Thread(null, r, name, 0);
            }
        }

        public static void main(String[] args) {
            for (int i = 0; i < 100; i++) {
                service.execute(() -> {
                    Date newDate = null;
                    try {
                        newDate = SIMPLE_DATE_FORMAT.parse("2021-06-05 11:45:59");
                    } catch (ParseException e) {
                        System.err.println(Thread.currentThread().getName() + ": " + e);
                    }
                    System.out.println(Thread.currentThread().getName() + ": " + newDate);
                });

            }
        }
    }
}
